package org.jimmy.tang.apache.httpclient;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

/**
 * @author jimmy
 * 
 */
public class HttpClientSample {

    private static final Logger logger = Logger
            .getLogger(HttpClientSample.class);

    public static final String getMethodURI = "http://10.140.29.45:8080/axis2/services/Version/getVersion";
    public static final String responseFile = "/tmp/test/response.html";
    public static final String responseFileWithWriter = "/tmp/test/responseWithWriter.html";

    /**
     * 
     * @param args
     * @throws HttpException
     * @throws IOException
     */
    public static void main(String[] args) throws HttpException, IOException {
        executeGetMethod(getMethodURI);
    }

    /**
     * 
     * @param backEndURI
     * @throws HttpException
     * @throws IOException
     */
    public static void executeGetMethod(String backEndURI)
            throws HttpException, IOException {
        logger.debug("Begin to execute get method.");
        HttpClient client = new HttpClient();

        // Set up HttpClient Get Method
        GetMethod getMethod = new GetMethod(backEndURI);

        int statusCode = client.executeMethod(getMethod);
        byte[] responseBody = getMethod.getResponseBody();
        logger.debug("Status code :" + statusCode);
        writeResponseToFile(responseFile, responseBody);
        writeResponseToFileByWriter(responseFileWithWriter, responseBody);
    }

    /**
     * 
     * @param filePath
     * @throws IOException
     */
    static void writeResponseToFile(String filePath, byte[] content)
            throws IOException {
        FileOutputStream fo = new FileOutputStream(filePath);
        BufferedOutputStream bo = new BufferedOutputStream(fo);
        bo.write(content);
        bo.flush();
        bo.close();
        fo.flush();
        fo.close();
    }

    /**
     * 
     * @param filePath
     * @param content
     * @throws IOException
     */
    static void writeResponseToFileByWriter(String filePath, byte[] content)
            throws IOException {
        FileWriter writer = new FileWriter(filePath);
        writer.write(new String(content));
        writer.flush();
        writer.close();
    }
}
